package com.LinkedList.learnSingleList;

import com.sh.Iterator;

public class SingleLinkedList implements List {

    private Node head = new Node();     // 头节点
    private int size = 0;


    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }


    @Override
    public boolean contains(Object o) {
        return indexOf(o) >= 0;
    }


    @Override
    public Node get(int index) {
        checkIndex(index);
        Node temp = this.head;
        for (int i = 0; i <= index; i++) {
            temp = temp.next;
        }
        return temp;
    }


    @Override
    public int indexOf(Object o) {
        return -1;
    }

    @Override
    public void add(int i, Object o) {
        Node temp = head;
        checkIndex(i);
        // 目标节点的上一个节点
        if (i > 0) {
            temp = get(i - 1);
        }
        Node newNode = new Node(o);
        newNode.next = temp.next;
        temp.next = newNode;
        size++;
    }

    // 加到最后
    @Override
    public void add(Object o) {
        add(size, o);
//        size++;
    }

    @Override
    public void addBefore(Object obj, Object e) {

    }

    @Override
    public void addAfter(Object obj, Object e) {

    }

    @Override
    public boolean remove(Object e) {
        return false;
    }

    @Override
    public Object remove(int index) {
        checkIndex(index);
        Node node = get(index - 1);
        Node temp = node.next;  // 防止内存泄漏
        node.next = node.next.next;
        temp.next = null;   // 防止内存泄漏
        size--;
        return null;
    }

    @Override
    public Object replace(int i, Object e) {
        return null;
    }

    @Override
    public Iterator interator() {
        return null;
    }

    public void checkIndex(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException("index is out of bounds");
        }
    }

    @Override
    public String toString() {
        Node temp = head.next;
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            sb.append(temp.data + " ");
            temp = temp.next;
        }

        return sb.toString();
    }
}
